package com.lms.netty.http;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;
import jdk.nashorn.internal.ir.CallNode;

import java.net.URI;
import java.nio.charset.Charset;

/**
 * @Author: 李孟帅
 * @CreateTime: 2020-06-16 13:49
 * @Description:
 */
public class NettyHttpServerHandler extends SimpleChannelInboundHandler<HttpObject> {

    /**
     * @Author 李孟帅
     * @Description 读取客户端数据
     * @Date 2020/6/16
     **/
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, HttpObject httpObject) throws Exception {

        if (httpObject instanceof HttpRequest){
            System.out.println("消息的类型："+httpObject.getClass());
            System.out.println("客户端地址："+ctx.channel().remoteAddress());

            HttpRequest httpRequest= (HttpRequest) httpObject;
            String uri = httpRequest.uri();
//            String path = new URI(uri).getPath();
            System.out.println("uri:"+uri);
            if ("/favicon.ico".equals(uri)){
                System.out.println("请求了"+uri+"不做响应");
                return;
            }

            //回复消息给浏览器
            ByteBuf content=Unpooled.copiedBuffer("hello,我是服务器", Charset.forName("GBK"));
            DefaultFullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, content);
            response.headers() 
                    .set(HttpHeaderNames.CONTENT_TYPE,"text/plain")
                    .set(HttpHeaderNames.CONTENT_LENGTH,content.readableBytes());
            //发送到缓冲区并刷新
            ctx.writeAndFlush(response);
        }

    }
}
